﻿// Inner Fire 游戏引擎库
// 简单地图类
//
// Copyright (c) 2024 by 尔西大帝. All rights reserved.
//
// 所属层级：应用层(4)
// 简单的设置地图类型
//
// Author: 尔西大帝
// Email: 2670613871@qq.com
// Created: 2024-12-11

#include "simple_map.h"
#include <enum_parser.h>
#include <graphics/graphics_def.h>
#include <iostream>
#include <klog.h>
#include <sstream>
#include <ctype.h>

namespace ifire::game {

static int char_to_value_safe(char c) {
  c = toupper(c); // 先统一转为大写

  if (c >= '0' && c <= '9') {
    return c - '0';
  }
  if (c >= 'A' && c <= 'Z') {
    return c - 'A' + 10;
  }
  return -1; // 非法字符
}

SimpleMap::SimpleMap(const eastl::string_view& filename) {
  XmlReader xml(filename.data());
  auto& root = xml.Root();

  // 载入基础属性
  IVec2 _size = root("Size");
  width = (int)_size.x;
  height = (int)_size.y;
  size = width * height;

  // 为Grid分配空间
  heights = std::make_unique<MapGrid<int>>(width, height);
  terrain = std::make_unique<MapGrid<int>>(width, height);
  props = std::make_unique<MapGrid<MapProp>>(width, height);

  // 载入Heights
  root.Foreach("Height", [this](XmlNode& n, int idx) {
    auto line = n.Value();
    for (size_t i = 0; i < width; i++) {
      auto c = char_to_value_safe(line[i]);
      heights->set(i, idx, c);
    }
  });

  root.Foreach("Terrain", [this](XmlNode& n, int idx) {
    auto line = n.Value();
    for (size_t i = 0; i < width; i++) {
      auto c = line[i];
      terrain->set(i, idx, c);
    }
  });

  root.Foreach("Props", [this](XmlNode& n, int idx) {
    auto line = n.Value();
    for (size_t i = 0; i < width; i += 2) {
      auto prop = line[i];
      auto type = char_to_value_safe(line[i + 1]);
      props->set(i, idx, {prop, type});
    }
  });
}

SimpleMap::~SimpleMap() {}

} // namespace ifire::game